import Vue from 'vue'
import VueRouter from 'vue-router'
import mainPart from '../views/mainPart.vue'
import login from '../views/login.vue'
import store from '../store/index'
import not_found from '../views/404/404.vue'
import center from '../views/center/center.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'mainPart',
    component: mainPart,
    children: [
      {
        path: 'center',
        name: 'center',
        component: center,
      },
    ],
  },
  {
    path: '/login',
    name: 'login',
    component: login,
  },
  {
    path: '/:path(.*)*',
    component: not_found,
  },
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes,
})
// 路由守卫
router.beforeEach((to, from, next) => {
  //去 login 直接去
  if (to.path === '/login') {
    next()
  }
  // 非 login 其他页面
  else {
    // 如果没有token就去login
    if (!localStorage.getItem('token_lg')) {
      next({ name: 'login' })
    } else {
      // 第一次登陆时会动态添加路由
      if (!store.state.isGetterRouter) {
        //
        addRouter()
        // console.log('第一次')
        // 此时next()无法直接放行到刚动态添加的的路由
        // 需写全路由地址
        next({ path: to.fullPath })
      }
      // 不是第一次登录并且有token_lg的话直接可以访问
      else {
        // console.log('不是第一次')
        next()
      }
    }
  }
})

import routers from './config'
// 动态添加路由
function addRouter() {
  routers.forEach((item) => {
    router.addRoute('mainPart', item)
  })
  store.commit('changeGetterRouter', true)
}
export default router
